/**
 * Created by tanbingqin on 2020/7/29.
 */
import { messages, deepFullCopy } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import constants from 'share/constants'
import { Button, Form, Switch, Input, Checkbox, Radio, InputNumber, Row, Col, message, Spin, Alert, Tooltip, Icon, Select, Affix, Popover } from 'antd'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
import formService from 'containers/setting/form/form.service'
import Chooser from 'components/chooser'
import errorMessage from 'share/errorMessage'
import formUtil from 'containers/setting/form/form-util'
import menuRoute from 'routes/menuRoute'

class RequestProperty extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      disabled: false, //所有表单适用这个属性
      form: {},  //表单信息
      setOfBooksId: '', //表单上的帐套
      priorityValue: {}, //所属组织，启用公司控件value
      priorityRangeValue: {}, //所属组织控件的rangeValue，包含整个对象信息
      isAlreadyNew: false, //是否是已经升级为新版差旅申请单
      isBudgetCa: false, //申请单提交时是否占用预算
      controlDimesion: [], //超申请管控类型 1001总金额，1002费用类型，1003分摊行管控
      overflowProportion: 0, //超申请管控允许超额百分之几
      isForce: 0, //超申请管控力度 0警告 1禁止
      isDeliverOther: false, //差旅，费用申请单是否转交给他人
      isLoanRelatedMore: 'Y', //差旅|费用申请单是否可被借款单关联多次，null & Y表示多次，N表示一次
      isRelatedMore: 'Y', //差旅|费用申请单是否可被报销多次，null & Y表示多次，N表示一次
      isRelatedNum: 'N', //差旅|费用申请单可被报销关联数量，null & N表示一张，Y表示多张
      isApplicationFund: false, //是否允许申请资金
      isAutoLoan: false, //创建申请单时是否同时创建借款单
      autoLoanLoading: false,
      autoLoanList: [], //创建申请单时可同时创建的借款单，length为1，单选
      isPurchaseApplication: false, //如果是费用申请单，是否是费用申请单下的采购申请单
    };
    this.formList = menuRoute.getRouteItem('form-list','key'); //表单列表页
  }

  componentDidMount() {
    this.initFormData();
    //处理表单属性
    this.initCustomFormPropertyMap();
  };

  initFormData = () => {
    const { form } = this.context;
    this.setState({
      form,
      disabled: !form.edit,
      setOfBooksId: form.setOfBooksId
    });
    //处理所属组织，启用公司
    this.initPriorityValue();
  };

  initCustomFormPropertyMap = () => {
    const { form } = this.context;
    let propertyMap = form.customFormPropertyMap;
    for (let key in propertyMap) {
      if (formUtil.getFieldKey(key, propertyMap[key])) {
        this.props.form.setFieldsValue(formUtil.getFieldKey(key, propertyMap[key]));
      }
      if (formUtil.getStateKey(key, propertyMap[key])) {
        this.setState(formUtil.getStateKey(key, propertyMap[key]));
      }
      if (key === 'document.overapplication') {
        let overApplicationConfig = JSON.parse(propertyMap[key]);
        this.setState({
          overflowProportion: overApplicationConfig.overflowProportion,
          isForce: overApplicationConfig.isForce,
          controlDimesion: overApplicationConfig.controlDimesion ? overApplicationConfig.controlDimesion : []
        });
      }
      if (key === 'application.direct.loan.type' && propertyMap[key]) {
        //过滤权限满足的，账套级分配的是否还存在以及获取表单名称
        let params = {
          formOIDs: [propertyMap[key]],
          companyOID: form.fromType === 1 ? form.companyOID : undefined
        };
        this.setState({autoLoanLoading: true});
        formService.getFormIsAutoLoan(params).then(res => {
          this.setState({autoLoanLoading: false});
          if (res.data && res.data.length) {
            let autoLoanList = [];
            res.data.map(relatedForm => {
              autoLoanList.push({formName: relatedForm.formName, formOID: relatedForm.formOID});
            });
            this.setState({autoLoanList});
          }
        });
      }
    }
  };

  initPriorityValue = () => {
    const { form } = this.context;
    let priorityValue = {
      levelCode: form.fromType === 3 ? "TENANT" : (form.fromType === 2 ? "SET_OF_BOOK" : "COMPANY"),
      levelOrgId: form.fromType === 3 ? form.tenantId : (form.fromType === 2 ? form.setOfBooksId : form.companyOID),
      levelOrgName: form.fromType === 3 ? form.tenantName : (form.fromType === 2 ? form.setOfBooksName : form.companyName)
    };
    if ((form.fromType === 2 || form.fromType === 3) && form.customFormCompanyRequest.visibleCompanyScope === '2') {
      priorityValue.enableCompany = 'PART';
      priorityValue.distribution = form.customFormCompanyRequest.companyList;
    }
    let priorityRangeValue = {};
    if (form.fromType === 2) {
      priorityRangeValue = {
        setOfBooksId: form.setOfBooksId,
        setOfBooksName: form.setOfBooksName
      }
    }
    if (form.fromType === 1) {
      priorityRangeValue = {
        id: form.companyId,
        companyOID: form.companyOID,
        name: form.companyName,
        setOfBooksId: form.setOfBooksId
      }
    }
    this.setState({priorityValue, priorityRangeValue});
  };

  handleStatusChange = (value, key) => {
    if (key === 'isApplicationFund' && value) {
      this.setState({isAutoLoan: true});
    }
    this.setState({
      [key]: value
    });
  };

  handleChangeAmount = (value, key) => {
    if (!isNaN(value) && value !== null && value !== undefined && value !== '') {
      this.setState({
        [key]: value
      });
    }
  };

  //value为true 说明要刷新列表，为event点击事件时不做刷新
  goBack = (value) => {
    const { close } = this.context;
    if (close) {
      close(value);
    } else {
      this.context.router.push(this.formList.url);
    }
  };

  handleSave = () => {
    const { formOID } = this.context;
    const { refreshBase } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err && this.validateData(values)) {
        let params = this.processValue(values);
        this.setState({loading: true});
        formService.saveNewForm(params).then(res => {
          this.setState({loading: false});
          message.success(messages('common.save.success',{arg1: res.data.formName})/*{arg1} 保存成功*/);
          refreshBase(formOID, 'property');
        }).catch((err) => {
          this.setState({loading: false});
          errorMessage(err.response);
        });
      }
    });
  };

  validateData = (values) => {
    const { formType } = this.context;
    const { isApplicationFund, isAutoLoan, autoLoanList, isBudgetCa, controlDimesion } = this.state;
    if ((formType === 2001 || formType === 2002) && isApplicationFund && isAutoLoan && !autoLoanList.length) {
      message.error(messages('request-2.key13')/*请选择需要同时创建的借款单*/);
      return false;
    }
    //差旅，费用申请单开启占预算，就必须勾选超申请管控类型
    if ((formType === 2001 || formType === 2002) && isBudgetCa && !controlDimesion.length) {
      message.error(messages('request-2.key364')/*申请单开启占预算，超申请管控为必填项！*/);
      return false;
    }
    return true;
  };

  processValue = (values) => {
    const { formType, formOID } = this.context;
    const { form } = this.state;
    let params = {
      ...form
    };
    //处理表单属性
    params.customFormPropertyMap = this.processPropertyMap(values);
    return params;
  };

  //处理表单属性
  processPropertyMap = (values) => {
    const { formType } = this.context;
    const { isRelatedMore, isLoanRelatedMore, isRelatedNum, isDeliverOther, isApplicationFund, isAutoLoan, autoLoanList,
      isForce, overflowProportion, controlDimesion, isBudgetCa } = this.state;
    let propertyMap = {};
    //申请单表单属性
    if (formType === 2001 || formType === 2002) {
      if (formType === 2001) {
        propertyMap['from.travel.relevance.application'] = isRelatedMore;
        propertyMap['application.property.customize.expense.type.enable'] = values.newTravel;
      }
      if (formType === 2002) {
        propertyMap['from.expense.relevance.application'] = isRelatedMore;
      }
      propertyMap['from.application.relevance.loan'] = isLoanRelatedMore;
      propertyMap['application.property.related.mutil.applications'] = isRelatedNum;
      propertyMap['application.property.deliver.others'] = isDeliverOther;
      propertyMap['application.funds'] = isApplicationFund;
      propertyMap['application.direct.loan.enabled'] = isAutoLoan;
      propertyMap['application.direct.loan.type'] = autoLoanList.length ? autoLoanList[0].formOID : '';
      propertyMap['document.overapplication'] = JSON.stringify({
        isForce,
        overflowProportion,
        controlDimesion: controlDimesion.length ? controlDimesion : []
      });
        propertyMap['budget.er.enabled'] = isBudgetCa;
    }
    return propertyMap;
  };

  render() {
    const { profile } = this.props;
    const { formType, formOID } = this.context;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { loading, disabled, isAlreadyNew, isBudgetCa, controlDimesion, overflowProportion, isForce, isDeliverOther,
      isLoanRelatedMore, isRelatedMore, isRelatedNum, isApplicationFund, isAutoLoan, autoLoanLoading, autoLoanList,
      priorityValue, isPurchaseApplication } = this.state;
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 8, offset: 1},
    };
    return (
      <div className="form-new-edit new-form form-detail-base">
        <Spin spinning={loading}>
          <Form>
            {formType === 2001 && profile['Customize.expense.type'] && formOID && (
              <div>
                <FormItem {...formItemLayout} label={messages('request-2.key365')/*升级新版申请单*/}>
                  {getFieldDecorator('newTravel', {
                    initialValue: false
                  })(
                    <RadioGroup disabled={disabled || isAlreadyNew}>
                      <Radio value={true}>{messages('common.yes')/*是*/}</Radio>
                      <Radio style={{marginLeft: 50}} value={false}>{messages('common.no')/*否*/}</Radio>
                    </RadioGroup>
                  )}
                  <div style={{color: '#989898'}}>{messages('request-2.key366')/*选择是，则此表单将升级成新版的申请单。可使用自定义的费用类型*/}</div>
                </FormItem>
                {getFieldValue('newTravel') && (
                  <FormItem {...formItemLayout} label={messages('request-2.key367')/*模式*/}>
                    <RadioGroup value="travelPlan" disabled={disabled}>
                      <Radio value="travelPlan">{messages('request-2.key368')/*差旅计划填写模式*/}</Radio>
                    </RadioGroup>
                    <div style={{color: '#989898'}}>{messages('request-2.key369')/*差旅计划填写模式即按出差日程的方式填写*/}</div>
                  </FormItem>
                )}
              </div>
            )}
            {(formType === 2001 || formType === 2002) &&
              <FormItem {...formItemLayout} label={messages('request-2.key59')/*提交时占用预算*/}>
                <RadioGroup
                  disabled={disabled}
                  value={isBudgetCa}
                  onChange={e => this.handleStatusChange(e.target.value, 'isBudgetCa')}
                >
                  <Radio value={true}>{messages('common.status.enable')/*启用*/}</Radio>
                  <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key418')/*不启用*/}</Radio>
                </RadioGroup>
                <div style={{color: '#989898'}}>
                  <div>{messages('request-2.key419')/*【不启用】预算，后续可改为【启用】预算；*/}</div>
                  <div>{messages('request-2.key420')/*【启用】预算并产生业务数据后，不可再改为【不启用】。*/}</div>
                </div>
              </FormItem>
            }
            {(formType === 2001 || formType === 2002) &&
              <div>
                <FormItem {...formItemLayout} label={messages('request-2.key67')/*超申请管控*/}>
                  <div className="group-line special-height normal-width">
                    <CheckboxGroup
                      value={controlDimesion}
                      disabled={disabled}
                      onChange={value => this.handleStatusChange(value, 'controlDimesion')}
                    >
                      <Row>
                        <Col span={8}><Checkbox value={1001}>{messages('request-2.key69')/*总金额管控*/}</Checkbox></Col>
                        <Col span={8}><Checkbox value={1002}>{messages('request-2.key70')/*费用类型管控*/}</Checkbox></Col>
                        <Col span={8}><Checkbox value={1003}>{messages('request-2.key71')/*分摊行管控*/}</Checkbox></Col>
                      </Row>
                    </CheckboxGroup>
                    <div style={{color: '#989898'}}>{messages('request-2.key68')/*开启超申请管控后请勿同时配置拆单！*/}</div>
                    <Row style={{marginTop: 16}}>
                      <Col span={8}>{messages('request-2.key72')/*控制力度*/}:</Col>
                      <Col span={16}>
                        <RadioGroup
                          value={isForce}
                          disabled={disabled}
                          onChange={e => this.handleStatusChange(e.target.value, 'isForce')}
                        >
                          <Radio value={0}>{messages('request-2.key73')/*警告*/}</Radio>
                          <Radio value={1}>{messages('request-2.key74')/*禁止*/}</Radio>
                        </RadioGroup>
                      </Col>
                    </Row>
                    <Row style={{marginTop: 16, marginBottom: 0}}>
                      <Col span={8}>{messages('request-2.key75')/*容差管控*/}:</Col>
                      <Col span={16}>
                        <span>{messages('request-2.key76')/*允许超过(%)*/}&nbsp;</span>
                        <InputNumber
                          style={{display: 'inline-block', width: 100}}
                          value={overflowProportion}
                          disabled={disabled}
                          onChange={num => this.handleChangeAmount(num, 'overflowProportion')}
                          min={0}
                          precision={2}
                        />
                      </Col>
                    </Row>
                  </div>
                </FormItem>
              </div>
            }
            {(formType === 2001 || (formType === 2002 && !isPurchaseApplication)) &&
              <div className="special-height">
                <FormItem {...formItemLayout} label={messages('request-2.key77')/*转交给他人*/}>
                  <RadioGroup
                    value={isDeliverOther}
                    disabled={disabled}
                    onChange={e => this.handleStatusChange(e.target.value, 'isDeliverOther')}
                  >
                    <Radio value={true}>{messages('request-2.key370')/*转交*/}</Radio>
                    <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key371')/*不转交*/}</Radio>
                  </RadioGroup>
                </FormItem>
              </div>
            }
            {(formType === 2001 || (formType === 2002 && !isPurchaseApplication)) &&
              <div className="special-height">
                <FormItem {...formItemLayout} label={messages('request-2.key84')/*申请单可被借款次数*/}>
                  <RadioGroup
                    disabled={disabled}
                    value={isLoanRelatedMore}
                    onChange={e => this.handleStatusChange(e.target.value, 'isLoanRelatedMore')}
                  >
                    <Radio value='Y'>{messages('request-2.key85')/*多次*/}</Radio>
                    <Radio style={{marginLeft: 50}} value='N'>{messages('request-2.key86')/*一次*/}</Radio>
                  </RadioGroup>
                </FormItem>
              </div>
            }
            {(formType === 2001 || (formType === 2002 && !isPurchaseApplication)) &&
              <div className="special-height">
                <FormItem {...formItemLayout} label={messages('request-2.key87')/*申请单可被报销次数*/}>
                  <RadioGroup
                    disabled={disabled}
                    value={isRelatedMore}
                    onChange={e => this.handleStatusChange(e.target.value, 'isRelatedMore')}
                  >
                    <Radio value='Y'>{messages('request-2.key85')/*多次*/}</Radio>
                    <Radio style={{marginLeft: 50}} value='N'>{messages('request-2.key86')/*一次*/}</Radio>
                  </RadioGroup>
                </FormItem>
              </div>
            }
            {(formType === 2001 || (formType === 2002 && !isPurchaseApplication)) &&
              <div className="special-height">
                <FormItem {...formItemLayout} label={messages('request-2.key88')/*报销关联多申请*/}>
                  <RadioGroup
                    disabled={disabled}
                    value={isRelatedNum}
                    onChange={e => this.handleStatusChange(e.target.value, 'isRelatedNum')}
                  >
                    <Radio value='Y'>{messages('request-2.key32')/*关联*/}</Radio>
                    <Radio style={{marginLeft: 50}} value='N'>{messages('request-2.key46')/*不关联*/}</Radio>
                  </RadioGroup>
                  <div style={{color: '#989898'}}>{messages('request-2.key89')/*开启关联多申请后，请确保对应的接口已调整完成。*/}</div>
                </FormItem>
              </div>
            }
            {(formType === 2001 || (formType === 2002 && !isPurchaseApplication)) &&
              <div className="special-height">
                <FormItem {...formItemLayout} label={messages('request-2.key90')/*允许申请资金*/}>
                  <RadioGroup
                    disabled={disabled}
                    value={isApplicationFund}
                    onChange={e => this.handleStatusChange(e.target.value, 'isApplicationFund')}
                  >
                    <Radio value={true}>{messages('common.yes')/*是*/}</Radio>
                    <Radio style={{marginLeft: 50}} value={false}>{messages('common.no')/*否*/}</Radio>
                  </RadioGroup>
                </FormItem>
                {isApplicationFund && (
                  <FormItem {...formItemLayout} label={messages('request-2.key91')/*申请资金类型*/}>
                    <RadioGroup
                      disabled={disabled}
                      value={isAutoLoan}
                      onChange={e => this.handleStatusChange(e.target.value, 'isAutoLoan')}
                    >
                      <Radio value={true}>{messages('request-2.key92')/*申请借款*/}</Radio>
                      <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key93')/*申请额度*/}</Radio>
                    </RadioGroup>
                    {isAutoLoan && (
                      <div>
                        <div style={{color: '#989898'}}>{messages('request-2.key94')/*申请单、借款单被分配的公司一致时，才可在创建申请单时，同时创建借款单。*/}</div>
                        <div className="normal-width">
                          <Chooser
                            placeholder={messages('common.select')/*请选择*/}
                            type='available_loan_form'
                            labelKey='formName'
                            valueKey='formOID'
                            disabled={autoLoanLoading || disabled || !priorityValue.levelOrgId}
                            onChange={value => this.handleStatusChange(value, 'autoLoanList')}
                            value={autoLoanList}
                            listExtraParams={{
                              setOfBooksId: priorityValue.levelCode === 'SET_OF_BOOK' ? priorityValue.levelOrgId : null,
                              companyOID: priorityValue.levelCode === 'COMPANY' ? priorityValue.levelOrgId : null,
                              isAll: true,
                              formTypeList: [2005, 2006]
                            }}
                            showNumber={false}
                            single={true}
                          />
                        </div>
                      </div>
                    )}
                    {!isAutoLoan && (
                      <div style={{color: '#989898'}}>
                        <div>{messages('request-2.key95')/*开启申请额度类型，需配合额度型商务卡使用；*/}</div>
                        <div>{messages('request-2.key96')/*开启申请额度不能与申请单变更功能共用，且参与人控件的安全性设置=同申请人。*/}</div>
                      </div>
                    )}
                  </FormItem>
                )}
              </div>
            }
          </Form>
        </Spin>
        <Affix offsetBottom={0} className="bottom-bar">
          {!disabled && (
            <Button type="primary" loading={loading} onClick={this.handleSave}>{messages('common.ok')/*确定*/}</Button>
          )}
          <Button style={{marginLeft: 15}} onClick={e => this.goBack(true)}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

RequestProperty.propTypes = {
  refreshBase: React.PropTypes.func
};

function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
    profile: state.login.profile
  }
}

RequestProperty.contextTypes = {
  formType: React.PropTypes.any,
  formOID: React.PropTypes.string,
  form: React.PropTypes.object,
  router: React.PropTypes.object,
  close: React.PropTypes.any
};

const WrappedRequestProperty = Form.create()(RequestProperty);

export default connect(mapStateToProps)(WrappedRequestProperty)
